<?php
namespace Application\Controller;

use Application\Model\Dao\UpdateDao;
use Application\Service\XmlService;
use Zend\Authentication\AuthenticationService;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Application\Service\ImageService;
use Application\Service\UpdateService;

/**
 * Class CommentController
 * @package Application\Controller
 *
 */
class CommentController extends LoginAwareController
{

    /*
     * Deleting a comment.
     */
    public function deleteCommentAction()
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $commentId = $request->getPost('commentId');
            $updateId = $request->getPost('updateId');
            $updateDao = $this->getServiceLocator()->get('update');
            $updateDao->deleteComment($commentId);
            return new JsonModel($this->processComment($updateDao->getCommentData(0, $updateId, 20)));
        }
    }

    /**
     * Comment on an update handling
     * @return \Zend\View\Model\JsonModel
     */
    public function commentAction()
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $comment = $request->getPost('comment');
            $updateId = $request->getPost('parentId');
            $updateDao = $this->getServiceLocator()->get('update');
            $loginId = $this->getLoggedinUserId();
            $updateDao->saveCommentData($comment, $loginId, $updateId, 'Update');
            return new JsonModel($this->processComment($updateDao->getCommentData(0, $updateId, 20)));
        }
    }

    /**
     * Pagination of comments on any parent Type.
     * @return JsonModel
     */
    public function getCommentsOnParent(){
        $request = $this->getRequest();
        $parentId = $request.getQuery('parentId');
        $noOfItems = $request.getQuery('noOfItems');
        $lastSeenId = $request.getQuery('lastSeenId');
        $updateDao = $this->getServiceLocator()->get('update');
        return new JsonModel($this->processComment($updateDao->getCommentData($lastSeenId, $parentId, $noOfItems)));
    }


    private function processComment($comments){
        foreach ($comments as $comment) {
            if ($this->getLoggedinUserId() == $comment->uid) {
                $comment->mine = true;
                $comment->commentor = 'You';
                $comment->date = date('d F h:i', strtotime($comment->date));
            }
        }
        return $comments;
    }
}

?>
